import argparse
from typing import List, Dict, Optional
from mcp.server.fastmcp import FastMCP
from loguru import logger
import sys

# 配置日志
logger.remove()
logger.add(sys.stderr, level="INFO")
logger.add("server.log", rotation="1 day", retention="7 days", level="DEBUG")

# 模拟数据存储
products_db = {
    "p1": {
        "id": "p1",
        "name": "MacBook Pro M3",
        "price": 12999.00,
        "category": "电脑数码",
        "description": "搭载 M3 芯片的 MacBook Pro",
        "stock": 50,
        "rating": 4.9
    },
    "p2": {
        "id": "p2",
        "name": "iPhone 15 Pro",
        "price": 8999.00,
        "category": "手机数码",
        "description": "最新款 iPhone",
        "stock": 100,
        "rating": 4.8
    }
}

shopping_carts = {}  # 用户购物车数据
wishlists = {}      # 用户心愿单数据

def create_mcp_instance(host: str, port: int) -> FastMCP:
    """
    创建并配置FastMCP实例
    :param host: 服务监听地址
    :param port: 服务端口号
    :return: 配置好的FastMCP实例
    """
    logger.info(f"正在创建FastMCP实例，监听地址: {host}:{port}")
    mcp = FastMCP(
        name="E-commerce_Assistant",
        host=host,
        port=port,
        description="电商助手服务，提供商品搜索、购物车管理、心愿单管理等功能",
        sse_path='/sse',  # 添加 SSE 路径
        cors_origins=["*"],  # 允许所有来源的跨域请求
        debug=True  # 启用调试模式
    )

    @mcp.tool()
    def search_products(
        keywords: str,
        category: str = None,
        min_price: float = None,
        max_price: float = None,
        sort_by: str = "relevance"
    ) -> Dict:
        """
        搜索商品
        :param keywords: 搜索关键词
        :param category: 商品类别
        :param min_price: 最低价格
        :param max_price: 最高价格
        :param sort_by: 排序方式(relevance/price_asc/price_desc/rating)
        :return: 搜索结果
        """
        logger.info(f"正在搜索商品: keywords={keywords}, category={category}")
        results = []
        for product in products_db.values():
            if keywords.lower() in product["name"].lower():
                if category and category != product["category"]:
                    continue
                if min_price and product["price"] < min_price:
                    continue
                if max_price and product["price"] > max_price:
                    continue
                results.append(product)
        
        if sort_by == "price_asc":
            results.sort(key=lambda x: x["price"])
        elif sort_by == "price_desc":
            results.sort(key=lambda x: x["price"], reverse=True)
        elif sort_by == "rating":
            results.sort(key=lambda x: x["rating"], reverse=True)
        
        logger.info(f"搜索完成，找到 {len(results)} 个商品")
        return {"products": results, "total": len(results)}

    @mcp.tool()
    def get_product_detail(product_id: str) -> Dict:
        """
        获取商品详情
        :param product_id: 商品ID
        :return: 商品详细信息
        """
        logger.info(f"正在获取商品详情: product_id={product_id}")
        if product_id not in products_db:
            logger.warning(f"商品不存在: {product_id}")
            return {"error": "商品不存在"}
        return products_db[product_id]

    @mcp.tool()
    def manage_shopping_cart(
        user_id: str,
        action: str,
        product_id: str = None,
        quantity: int = 1
    ) -> Dict:
        """
        购物车管理
        :param user_id: 用户ID
        :param action: 操作类型(add/remove/update/list/clear)
        :param product_id: 商品ID
        :param quantity: 商品数量
        :return: 购物车信息
        """
        logger.info(f"正在管理购物车: user_id={user_id}, action={action}")
        if user_id not in shopping_carts:
            shopping_carts[user_id] = {}
        
        cart = shopping_carts[user_id]
        
        if action == "add":
            if product_id not in products_db:
                logger.warning(f"商品不存在: {product_id}")
                return {"error": "商品不存在"}
            if product_id in cart:
                cart[product_id]["quantity"] += quantity
            else:
                cart[product_id] = {
                    "product": products_db[product_id],
                    "quantity": quantity
                }
        elif action == "remove":
            if product_id in cart:
                del cart[product_id]
        elif action == "update":
            if product_id in cart:
                cart[product_id]["quantity"] = quantity
        elif action == "clear":
            cart.clear()
        
        return {"cart": cart, "total_items": sum(item["quantity"] for item in cart.values())}

    @mcp.tool()
    def manage_wishlist(
        user_id: str,
        action: str,
        product_id: str = None,
        note: str = None
    ) -> Dict:
        """
        心愿单管理
        :param user_id: 用户ID
        :param action: 操作类型(add/remove/list)
        :param product_id: 商品ID
        :param note: 备注
        :return: 心愿单信息
        """
        logger.info(f"正在管理心愿单: user_id={user_id}, action={action}")
        if user_id not in wishlists:
            wishlists[user_id] = {}
        
        wishlist = wishlists[user_id]
        
        if action == "add":
            if product_id not in products_db:
                logger.warning(f"商品不存在: {product_id}")
                return {"error": "商品不存在"}
            wishlist[product_id] = {
                "product": products_db[product_id],
                "note": note
            }
        elif action == "remove":
            if product_id in wishlist:
                del wishlist[product_id]
        
        return {"wishlist": wishlist, "total_items": len(wishlist)}

    @mcp.tool()
    def get_similar_products(product_id: str, limit: int = 5) -> Dict:
        """
        获取相似商品推荐
        :param product_id: 商品ID
        :param limit: 返回数量
        :return: 相似商品列表
        """
        logger.info(f"正在获取相似商品: product_id={product_id}, limit={limit}")
        if product_id not in products_db:
            logger.warning(f"商品不存在: {product_id}")
            return {"error": "商品不存在"}
        
        target = products_db[product_id]
        similar = []
        
        for pid, product in products_db.items():
            if pid != product_id and product["category"] == target["category"]:
                similar.append(product)
                if len(similar) >= limit:
                    break
        
        return {"products": similar, "total": len(similar)}

    return mcp

def main():
    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(description='E-commerce Assistant MCP SSE Server')
    parser.add_argument('--port', type=int, default=8080, help='SSE服务端口号（默认：8080）')
    parser.add_argument('--host', default='127.0.0.1', help='SSE服务监听地址（默认：127.0.0.1）')
    args = parser.parse_args()

    try:
        # 创建并配置MCP实例
        mcp = create_mcp_instance(args.host, args.port)

        print(f"Starting E-commerce Assistant MCP SSE server on {args.host}:{args.port}")
        print("Available tools:")
        print("- search_products: 搜索商品")
        print("- get_product_detail: 获取商品详情")
        print("- manage_shopping_cart: 购物车管理")
        print("- manage_wishlist: 心愿单管理")
        print("- get_similar_products: 获取相似商品推荐")
        
        # 启动服务器
        mcp.run(transport='sse')
        
    except Exception as e:
        logger.error(f"服务器启动失败: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main() 